<template>
  <div class="page-content">
    <div class="header">
      <h3>设备扫描</h3>
      <p class="header-desc">扫描并管理您的网络和ADB设备</p>
    </div>

    <!-- 无ADB设备扫描部分 -->
    <div class="section-container">
      <div class="section-header">
        <h4>无ADB设备扫描</h4>
      </div>

      <el-card class="scan-main-card">
        <div class="control-result-container">
          <div class="control-panel">
            <div class="panel-header">
              <h5>扫描控制</h5>
            </div>
            
            <div class="scan-settings">
              <el-form label-position="top">
                <el-form-item label="IP范围">
                  <el-row :gutter="8">
                    <el-col :span="11">
                      <el-input v-model="networkScanRange.startIp" placeholder="起始IP" size="default" />
                    </el-col>
                    <el-col :span="2" class="text-center range-separator">
                      至
                    </el-col>
                    <el-col :span="11">
                      <el-input v-model="networkScanRange.endIp" placeholder="结束IP" size="default" />
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item label="扫描端口">
                  <el-input v-model="networkScanPort" placeholder="扫描端口" size="default" />
                </el-form-item>
              </el-form>
              
              <div class="action-buttons">
                <el-button type="primary" :loading="isNetworkScanning" @click="startNetworkScan" v-ripple>
                  {{ isNetworkScanning ? '扫描中...' : '开始扫描' }}
                </el-button>
                <el-button @click="stopNetworkScan" :disabled="!isNetworkScanning" v-ripple>停止扫描</el-button>
              </div>
            </div>
          </div>
          
          <div class="result-panel">
            <div class="panel-header with-actions">
              <h5>扫描结果 <el-badge :value="networkDeviceList.length" /></h5>
              <div class="panel-actions">
                <el-button size="small" @click="refreshNetworkDevices" v-ripple>刷新列表</el-button>
                <el-button size="small" type="danger" @click="clearNetworkResults" :disabled="networkDeviceList.length === 0" v-ripple>清空结果</el-button>
              </div>
            </div>
            
            <div class="result-content">
              <el-table v-loading="isNetworkScanning" :data="networkDeviceList" stripe border style="width: 100%">
                <el-table-column prop="host" label="IP地址" width="150" />
                <el-table-column label="制造商" width="120">
                  <template #default="scope">
                    {{ scope.row.device_info?.manufacturer }}
                  </template>
                </el-table-column>
                <el-table-column label="设备型号" width="120">
                  <template #default="scope">
                    {{ scope.row.device_info?.model }}
                  </template>
                </el-table-column>
                <el-table-column label="设备码" width="180">
                  <template #default="scope">
                    {{ scope.row.device_info?.serial }}
                  </template>
                </el-table-column>
                <el-table-column label="安卓版本" width="100">
                  <template #default="scope">
                    {{ scope.row.device_info?.os_version }}
                  </template>
                </el-table-column>
                <el-table-column label="SDK版本" width="100">
                  <template #default="scope">
                    {{ scope.row.device_info?.sdk_version }}
                  </template>
                </el-table-column>
                <el-table-column label="硬件" width="100">
                  <template #default="scope">
                    {{ scope.row.device_info?.hardware }}
                  </template>
                </el-table-column>
                <el-table-column label="磁盘使用" width="150">
                  <template #default="scope">
                    {{ scope.row.device_info?.disk_usage }}
                  </template>
                </el-table-column>
              </el-table>
              
              <div v-if="networkDeviceList.length === 0 && !isNetworkScanning" class="no-data">
                <el-empty description="暂无扫描结果" />
              </div>

              <div class="batch-actions" v-if="networkDeviceList.length > 0">
                <el-button 
                  type="primary" 
                  @click="batchImportNetwork"
                  :loading="isImporting"
                  :disabled="isImporting"
                >一键入库</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- ADB设备扫描部分 -->
    <div class="section-container">
      <div class="section-header">
        <h4>ADB设备扫描</h4>
      </div>

      <el-card class="scan-main-card">
        <div class="control-result-container">
          <!-- 左侧控制区域 -->
          <div class="control-panel">
            <div class="panel-header">
              <h5>扫描控制</h5>
            </div>
            
            <div class="scan-settings">
              <el-form label-position="top">
                <el-form-item label="扫描节点">
                  <el-select 
                    v-model="selectedAdbScanNodeId" 
                    placeholder="选择节点" 
                    style="width: 100%"
                    :loading="isNodeLoading"
                  >
                    <el-option
                      v-for="node in nodeList"
                      :key="node.service_id"
                      :label="node.service_name"
                      :value="node.service_id"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
              
              <div class="action-buttons">
                <el-button type="primary" :loading="isAdbScanning" @click="startAdbScan" v-ripple :disabled="!selectedAdbScanNodeId">
                  {{ isAdbScanning ? '扫描中...' : '开始扫描' }}
                </el-button>
                <el-button @click="stopAdbScan" :disabled="!isAdbScanning" v-ripple>停止扫描</el-button>
              </div>
            </div>
          </div>
          
          <!-- 右侧结果区域 -->
          <div class="result-panel">
            <div class="panel-header with-actions">
              <h5>ADB设备 <el-badge :value="adbDeviceList.length" /></h5>
              <div class="panel-actions">
                <el-button size="small" @click="refreshAdbDevices" v-ripple>刷新列表</el-button>
                <el-button size="small" type="danger" @click="clearAdbResults" :disabled="adbDeviceList.length === 0" v-ripple>清空结果</el-button>
              </div>
            </div>
            
            <div class="result-content">
              <el-table 
                v-loading="isAdbScanning" 
                :data="adbDeviceList" 
                stripe 
                border 
                style="width: 100%"
                @selection-change="selectedAdbDevices = $event.map(item => item.device_id)"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="device_id" label="设备码" width="180" />
                <el-table-column prop="model" label="手机序列号" />
                <el-table-column prop="android_version" label="安卓版本" width="100" />
                <el-table-column prop="cpu_arch" label="架构" width="120" />
                <el-table-column prop="cpu_cores" label="核数" width="80" />
                <el-table-column prop="mac_address" label="MAC地址" width="150" />
                <el-table-column prop="processor" label="厂商" width="120" />
              </el-table>
              
              <div v-if="adbDeviceList.length === 0 && !isAdbScanning" class="no-data">
                <el-empty description="未检测到ADB设备" />
              </div>

              <div class="batch-actions" v-if="adbDeviceList.length > 0">
                <el-button 
                  type="primary" 
                  @click="batchImport" 
                  :disabled="selectedAdbDevices.length === 0 || isImporting"
                  :loading="isImporting"
                >批量入库</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 节点选择对话框 -->
    <el-dialog
      title="选择节点"
      v-model="nodeSelectVisible"
      width="30%"
      class="custom-dialog"
    >
      <el-form>
        <el-form-item label="选择节点">
          <el-select v-model="selectedNodeId" placeholder="请选择节点" style="width: 100%">
            <el-option
              v-for="node in nodeList"
              :key="node.service_id"
              :label="node.service_name"
              :value="node.service_id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="nodeSelectVisible = false" :disabled="isImporting">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmNodeSelect" 
            :loading="isImporting"
            :disabled="isImporting"
          >确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAdbDeviceList, 
  getServerInfo, 
  scanDevices, 
  getServerDevices, 
  batchOpenPort, 
  connectDeviceAndAddToDB,
  registerDevice,
  getNodeList 
} from '@/Newapi/device'

// =============== 网络设备扫描 ===============
// 扫描状态
const isNetworkScanning = ref(false)

// 扫描配置
const networkScanRange = reactive({
  startIp: '192.168.31.1',
  endIp: '192.168.31.255'
})
const networkScanPort = ref('50001')

// 设备列表
const networkDeviceList = ref<any[]>([])

// 开始网络扫描
const startNetworkScan = async () => {
  if (isNetworkScanning.value) return
  
  // 验证输入
  if (!networkScanRange.startIp || !networkScanRange.endIp) {
    ElMessage.warning('请输入完整的IP范围')
    return
  }
  
  if (!networkScanPort.value) {
    ElMessage.warning('请输入扫描端口')
    return
  }
  
  isNetworkScanning.value = true
  ElMessage.success('开始扫描网络设备，请稍候...')
  
  try {
    // 发送扫描请求
    const scanResult = await scanDevices({
      start_ip: networkScanRange.startIp,
      end_ip: networkScanRange.endIp,
      port: parseInt(networkScanPort.value)
    })
    
    ElMessage.info(scanResult.data.msg || '扫描完成')
    
    // 获取设备列表
    await fetchNetworkDevices()
  } catch (error) {
    console.error('扫描网络设备出错:', error)
    ElMessage.error('扫描出错，请重试')
  } finally {
    isNetworkScanning.value = false
  }
}

// 获取设备列表
const fetchNetworkDevices = async () => {
  try {
    const res = await getServerDevices()
    if (res.data && res.data.code === 0) {
      networkDeviceList.value = res.data.data?.servers || []
    } else {
      ElMessage.warning('获取设备列表失败')
    }
  } catch (error) {
    console.error('获取设备列表出错:', error)
    ElMessage.error('获取设备列表失败，请重试')
  }
}

// 刷新网络设备列表
const refreshNetworkDevices = () => {
  ElMessage.info('刷新设备列表')
  fetchNetworkDevices()
}

// 停止网络扫描
const stopNetworkScan = () => {
  if (!isNetworkScanning.value) return
  
  isNetworkScanning.value = false
  ElMessage.info('网络设备扫描已停止')
}

// 清空网络扫描结果
const clearNetworkResults = () => {
  ElMessageBox.confirm('确定要清空所有网络扫描结果吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    networkDeviceList.value = []
    ElMessage.success('网络扫描结果已清空')
  }).catch(() => {})
}

// =============== ADB设备扫描 ===============
// ADB扫描状态
const isAdbScanning = ref(false)

// ADB设备列表
const adbDeviceList = ref<any[]>([])

// 选中的设备列表
const selectedAdbDevices = ref<string[]>([])

// 节点选择相关
const nodeSelectVisible = ref(false)
const selectedNodeId = ref('')
const selectedAdbScanNodeId = ref('') // 专门用于ADB扫描的节点选择
const nodeList = ref<any[]>([])
const currentAction = ref<'network' | 'adb'>('network')
const isImporting = ref(false)  // 添加入库加载状态
const isNodeLoading = ref(false) // 节点加载状态

// 获取节点列表
const fetchNodeList = async () => {
  try {
    isNodeLoading.value = true
    const result = await getNodeList()
    if (result.code === 200) {
      nodeList.value = Object.entries(result.data).map(([key, node]: [string, any]) => ({
        service_id: node.service_id,
        service_name: node.service_name
      }))
    } else {
      ElMessage.error(result.msg || '获取节点列表失败')
    }
  } catch (error) {
    console.error('获取节点列表失败:', error)
    ElMessage.error('获取节点列表失败')
  } finally {
    isNodeLoading.value = false
  }
}

// 开始ADB扫描
const startAdbScan = async () => {
  if (isAdbScanning.value) return
  
  // 检查是否已选择节点
  if (!selectedAdbScanNodeId.value) {
    ElMessage.warning('请先选择要扫描的节点')
    return
  }
  
  // 查找选中的节点
  const selectedNode = nodeList.value.find(node => node.service_id === selectedAdbScanNodeId.value)
  if (!selectedNode) {
    ElMessage.error('所选节点无效')
    return
  }
  
  // 直接执行扫描
  await scanAdbDevices(selectedNode.service_name)
}

// 实际执行ADB设备扫描
const scanAdbDevices = async (serviceName: string) => {
  isAdbScanning.value = true
  ElMessage.success(`开始扫描节点 ${serviceName} 的ADB设备，请稍候...`)
  
  try {
    const response = await getAdbDeviceList(serviceName)
    if (response.code === 200 && response.data.success) {
      adbDeviceList.value = response.data.data
      ElMessage.success(`扫描完成，发现 ${response.data.count} 台设备`)
    } else {
      ElMessage.error(response.msg || '扫描失败')
    }
  } catch (error) {
    ElMessage.error('扫描出错，请重试')
    console.error('ADB扫描错误:', error)
  } finally {
    isAdbScanning.value = false
  }
}

// 确认节点选择
const confirmNodeSelect = async () => {
  if (!selectedNodeId.value) {
    ElMessage.warning('请选择节点')
    return
  }

  const selectedNode = nodeList.value.find(node => node.service_id === selectedNodeId.value)
  if (!selectedNode) {
    ElMessage.error('所选节点无效')
    return
  }

  nodeSelectVisible.value = false

  if (currentAction.value === 'network') {
    await batchImportNetworkWithNode(selectedNode.service_name)
  } else if (currentAction.value === 'adb') {
    await batchImportAdbWithNode(selectedNode.service_name)
  }
}

// 修改批量入库网络设备的函数
const batchImportNetwork = async () => {
  currentAction.value = 'network'
  await fetchNodeList()
  nodeSelectVisible.value = true
}

// 实际执行网络设备入库
const batchImportNetworkWithNode = async (serviceName: string) => {
  if (networkDeviceList.value.length === 0) {
    ElMessage.warning('没有可入库的设备')
    return
  }

  if (isImporting.value) {
    ElMessage.warning('正在入库中，请稍候...')
    return
  }

  try {
    isImporting.value = true
    const result = await registerDevice(serviceName)
    if (result.code === 200) {
      const registerResults = result.data.results || []
      const summary = result.data.summary || {}
      
      registerResults.forEach(serverResult => {
        if (serverResult.success) {
          ElMessage.success(`服务器 ${serverResult.server_addr} 注册成功，新增 ${serverResult.device_count} 台设备`)
        } else {
          ElMessage.warning({
            message: `服务器 ${serverResult.server_addr} ${serverResult.message}`,
            duration: 5000
          })
        }
      })

      ElMessage({
        type: summary.success_count > 0 ? 'success' : 'info',
        message: `注册结果统计：
          共有 ${summary.total_servers} 个服务器，
          成功注册 ${summary.success_count} 台设备，
          设备总数 ${summary.total_devices} 台`,
        duration: 5000,
        showClose: true
      })

      await refreshNetworkDevices()
    } else {
      ElMessage.error(result.msg || '入库失败')
    }
  } catch (error) {
    console.error('入库出错:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    isImporting.value = false
  }
}

// 修改批量入库ADB设备的函数
const batchImport = async () => {
  if (selectedAdbDevices.value.length === 0) {
    ElMessage.warning('请先选择要入库的设备')
    return
  }

  currentAction.value = 'adb'
  await fetchNodeList()
  nodeSelectVisible.value = true
}

// 实际执行ADB设备入库
const batchImportAdbWithNode = async (serviceName: string) => {
  if (isImporting.value) {
    ElMessage.warning('正在入库中，请稍候...')
    return
  }

  try {
    isImporting.value = true
    ElMessage.success('正在开启设备端口...')
    
    const result = await batchOpenPort({
      service_name: serviceName,
      device_list: selectedAdbDevices.value
    })
    
    if (result.code === 200) {
      ElMessage.success('正在连接设备并入库...')
      const connectResult = await connectDeviceAndAddToDB(serviceName)
      
      if (connectResult.code === 200 && connectResult.data.success) {
        const deviceCount = connectResult.data.count
        const deviceInfo = connectResult.data.data[0]
        
        ElMessage.success(`批量入库成功，共入库 ${deviceCount} 台设备`)
        
        if (deviceInfo) {
          ElMessage.success(`
            设备信息：
            设备码：${deviceInfo.device_id}
            型号：${deviceInfo.model}
            安卓版本：${deviceInfo.android_version}
            处理器：${deviceInfo.processor}
            CPU架构：${deviceInfo.cpu_arch}
            CPU核数：${deviceInfo.cpu_cores}
            MAC地址：${deviceInfo.mac_address}
          `)
        }
        
        selectedAdbDevices.value = []
        await refreshAdbDevices()
      } else {
        ElMessage.error(connectResult.msg || '设备入库失败')
        console.log(connectResult.msg)
      }
    } else {
      ElMessage.error('批量开启端口失败')
    }
  } catch (error) {
    console.error('批量入库出错:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    isImporting.value = false
  }
}

// 刷新ADB设备列表
const refreshAdbDevices = async () => {
  if (!selectedAdbScanNodeId.value) {
    ElMessage.warning('请先选择要扫描的节点')
    return
  }
  
  ElMessage.info('刷新ADB设备列表')
  await startAdbScan()
}

// 清空ADB扫描结果
const clearAdbResults = () => {
  ElMessageBox.confirm('确定要清空所有ADB设备列表吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    adbDeviceList.value = []
    ElMessage.success('ADB设备列表已清空')
  }).catch(() => {})
}

// 停止ADB扫描
const stopAdbScan = () => {
  if (!isAdbScanning.value) return
  
  isAdbScanning.value = false
  ElMessage.info('ADB设备扫描已停止')
}

// 页面初始化
onMounted(async () => {
  // 初始化获取节点列表
  await fetchNodeList()
})
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;
  padding: 15px;
  
  .header {
    margin-bottom: 25px;
    padding-bottom: 15px;
    border-bottom: 1px solid var(--el-border-color-light);
    
    h3 {
      font-size: 20px;
      font-weight: 600;
      margin-bottom: 8px;
      color: var(--el-text-color-primary);
    }
    
    .header-desc {
      font-size: 14px;
      color: var(--el-text-color-secondary);
      margin: 0;
    }
  }
  
  .section-container {
    margin-bottom: 30px;
  }

  .section-header {
    margin-bottom: 16px;
    
    h4 {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      position: relative;
      padding-left: 12px;
      margin: 0;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 3px;
        height: 16px;
        background-color: var(--el-color-primary);
        border-radius: 2px;
      }
    }
  }
  
  .scan-main-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    :deep(.el-card__body) {
      padding: 0;
    }
  }
  
  .control-result-container {
    display: flex;
    min-height: 400px;
    
    .control-panel {
      flex: 0 0 300px;
      border-right: 1px solid var(--el-border-color-lighter);
      display: flex;
      flex-direction: column;
      
      .scan-settings {
        padding: 16px;
        flex-grow: 1;
        
        .action-buttons {
          margin-top: 20px;
          display: flex;
          gap: 10px;
        }
      }
    }
    
    .result-panel {
      flex: 1;
      display: flex;
      flex-direction: column;
      
      .result-content {
        padding: 16px;
        flex-grow: 1;
        
        .no-data {
          display: flex;
          justify-content: center;
          padding: 40px 0;
        }
        
        .batch-actions {
          margin-top: 16px;
          display: flex;
          justify-content: flex-end;
        }
      }
    }
  }
  
  .panel-header {
    height: 50px;
    display: flex;
    align-items: center;
    padding: 0 16px;
    background-color: var(--el-fill-color-light);
    border-bottom: 1px solid var(--el-border-color-lighter);
    
    h5 {
      margin: 0;
      font-size: 15px;
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
    
    &.with-actions {
      justify-content: space-between;
      
      .panel-actions {
        display: flex;
        gap: 8px;
      }
    }
  }
  
  .range-separator {
    display: flex;
    justify-content: center;
    align-items: center;
    color: var(--el-text-color-secondary);
  }
  
  // 表单样式优化
  :deep(.el-form-item__label) {
    padding-bottom: 4px;
    line-height: 1.5;
    font-weight: 500;
    color: var(--el-text-color-primary);
  }
  
  // 表格样式优化
  :deep(.el-table) {
    --el-table-border-color: var(--el-border-color-lighter);
    --el-table-header-bg-color: var(--el-fill-color-light);
    --el-table-row-hover-bg-color: var(--el-fill-color);
    
    th {
      font-weight: 500;
    }
  }
  
  // 对话框样式
  :deep(.custom-dialog) {
    .el-dialog__header {
      margin: 0;
      padding: 15px 20px;
      border-bottom: 1px solid var(--el-border-color-lighter);
    }
    
    .el-dialog__footer {
      border-top: 1px solid var(--el-border-color-lighter);
      padding: 10px 20px;
    }
  }
}

// 响应式布局
@media screen and (max-width: 1200px) {
  .control-result-container {
    flex-direction: column;
    
    .control-panel {
      flex: none;
      width: 100%;
      border-right: none;
      border-bottom: 1px solid var(--el-border-color-lighter);
    }
  }
}

@media screen and (max-width: 768px) {
  .page-content {
    padding: 10px;
  }
}
</style> 